from ..repositories import user_setting_repositories, users_repository
from ..utils.password_utils import encrypt_password, decrypt_password
import re


async def validate_password_data(current_password, new_password):
    """
    验证密码数据
    :param current_password: 当前密码
    :param new_password: 新密码
    :return: (bool, str) - (验证是否通过, 错误信息)
    """
    if not current_password or not new_password:
        return False, "密码不能为空"
    if len(new_password) < 6:
        return False, "新密码长度不能小于6位"
    return True, ""

async def validate_phone_data(phone, verify_code):
    """
    验证手机号和验证码数据
    :param phone: 手机号
    :param verify_code: 验证码
    :return: (bool, str) - (验证是否通过, 错误信息)
    """
    if not phone or not phone.isdigit() or len(phone) != 11:
        return False, "请输入有效的11位手机号码"
    if not re.match(r'^1[3-9]\d{9}$', phone):
        return False, "请输入有效的手机号格式"
    if not verify_code or not verify_code.isdigit() or len(verify_code) != 4:
        return False, "验证码必须是4位数字"
    return True, ""

async def validate_username_data(username):
    """
    验证用户名数据
    :param username: 用户名
    :return: (bool, str) - (验证是否通过, 错误信息)
    """
    if not username:
        return False, "用户名不能为空"
    if len(username) < 4 or len(username) > 20:
        return False, "用户名长度必须在4-20个字符之间"
    return True, ""

async def update_password(user_id, current_password, new_password):
    """
    更新用户密码
    :param user_id: 用户ID
    :param current_password: 当前密码
    :param new_password: 新密码
    :return: 更新结果
    """
    try:
        is_valid, error_message = await validate_password_data(current_password, new_password)
        if not is_valid:
            return {"code": 1000, "message": error_message}
            
        # 加密新密码
        encrypted_current_password = encrypt_password(current_password)
        encrypted_new_password = encrypt_password(new_password)
        result = await user_setting_repositories.update_password(user_id, encrypted_current_password, encrypted_new_password)
        if result:
            return {"code": 0, "message": "密码更新成功，请重新登录"}
        return {"code": 1, "message": "当前密码错误"}
    except Exception as e:
        print(f"修改密码失败: {str(e)}")
        return {"code": 1, "message": f"修改密码失败: {str(e)}"}

async def update_phone(user_id, current_password, new_phone, verify_code):
    """
    更新手机号
    :param user_id: 用户ID
    :param current_password: 当前密码
    :param new_phone: 新手机号
    :param verify_code: 验证码
    :return: 更新结果
    """
    try:
        is_valid, error_message = await validate_phone_data(new_phone, verify_code)
        if not is_valid:
            return {"code": 1000, "message": error_message}

        # 从数据库获取有效验证码
        valid_code = await users_repository.get_valid_code(new_phone)
        if not valid_code:
            return False, "验证码已过期或不存在"

        if decrypt_password(valid_code['code']) != verify_code:
            return False, "验证码错误"
            
        result = await user_setting_repositories.update_phone(user_id, current_password, new_phone)
        if result:
            return {"code": 0, "message": "手机号更新成功"}
        return {"code": 1, "message": "手机号更新失败"}
    except Exception as e:
        print(f"修改手机号失败: {str(e)}")
        return {"code": 1, "message": f"修改手机号失败: {str(e)}"}

async def update_username(user_id, new_username):
    """
    更新用户名
    :param user_id: 用户ID
    :param new_username: 新用户名
    :return: 更新结果
    """
    try:
        is_valid, error_message = await validate_username_data(new_username)
        if not is_valid:
            return {"code": 1000, "message": error_message}
            
        result = await user_setting_repositories.update_username(user_id, new_username)
        if result:
            return {"code": 0, "message": "用户名更新成功"}
        return {"code": 1, "message": "用户名更新失败"}
    except Exception as e:
        print(f"修改用户名失败: {str(e)}")
        return {"code": 1, "message": f"修改用户名失败: {str(e)}"}

async def get_user_info(user_id):
    """
    获取用户信息
    :param user_id: 用户ID
    :return: 用户信息
    """
    try:
        user_info = await user_setting_repositories.get_user_info(user_id)
        if user_info:
            return {
                "code": 0,
                "message": "获取用户信息成功",
                "data": {
                    "username": {"username": user_info["username"]},
                    "phone": user_info["phone"]
                }
            }
        return {"code": 1, "message": "获取用户信息失败"}
    except Exception as e:
        print(f"获取用户信息失败: {str(e)}")
        return {"code": 1, "message": f"获取用户信息失败: {str(e)}"}
